package com.py.pythink.third;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class JwtUtil {
    //生成
    public static String createJwt(String msg) {
        //指定签名的算法
        SignatureAlgorithm algorithm = SignatureAlgorithm.HS256;
        //建造者对象
        JwtBuilder jwtBuilder = Jwts.builder().
                signWith(algorithm,createKey()). //设置签名的密匙
                setId(UUID.randomUUID().toString()). //设置唯一标记，防止：重放攻击
                setIssuedAt(new Date()). //设置生成的时间
                setSubject(msg); //设置存储的内容
        //生成令牌
        return jwtBuilder.compact();
    }

    //解析
    public static String parseJwt(String jwt) {
        return Jwts.parser().
                setSigningKey(createKey()).
                parseClaimsJws(jwt).
                getBody().
                getSubject();

    }
    //生成密匙
    private static Key createKey(){
        String key = "pythink_py";
        SecretKey aes = new SecretKeySpec(Base64.getEncoder().encode(key.getBytes()), "AES");
        return aes;
    }
}
